﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Model;
using Aioms.Models;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using SqlSugar;

namespace Aioms.Controllers
{
    [DynamicApiController]
    public class RoleController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public RoleController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="doPage"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostList([FromForm] long eid, [FromForm] int doPage, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10)
        {
            List<Role> roles;
            RefAsync<int> total = 0;
            if (doPage == 1)
            {
                roles = await db.Queryable<Role>().Where(r => r.Eid == eid).ToPageListAsync(pageIndex, pageSize, total);
            }
            else
            {
                roles = await db.Queryable<Role>().Where(r => r.Eid == eid).ToListAsync();
            }

            JArray ja_role = new();
            if (roles?.Count > 0)
            {
                foreach (Role role in roles)
                {
                    List<long> epids = await db.Queryable<RoleEmployee>().Where(ru => ru.Eid == eid && ru.Rid == role.Id).Select(ru => ru.Epid).ToListAsync();
                    epids.Add(-1);
                    List<Employee> employees = await db.Queryable<Employee>().Where(u => epids.Contains(u.Id)).ToListAsync();
                    // 查询出来所有角色的用户
                    JObject jo_role = JObject.FromObject(role);
                    jo_role.Add("employees", employees == null ? null : JArray.FromObject(employees));
                    ja_role.Add(jo_role);
                }
            }

            UnifyContext.Fill(new { Total = total.Value });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = ja_role,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="role"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostSave([FromForm] long eid, [FromForm] Role role)
        {
            await db.Insertable<Role>(role).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDelete([FromForm] long eid, [FromForm] long id)
        {
            // 删除该角色所有的用户
            await db.Deleteable<RoleEmployee>().Where(ru => ru.Eid == eid && ru.Rid == id).ExecuteCommandAsync();
            // 删除该角色所有权限
            await db.Deleteable<RolePermission>().Where(ru => ru.Eid == eid && ru.Rid == id).ExecuteCommandAsync();

            await db.Deleteable<Role>().Where(r => r.Eid == eid && r.Id == id).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="role"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdate([FromForm] long eid, [FromForm] Role role)
        {
            await db.Updateable<Role>(role).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShow([FromForm] long eid, [FromForm] long id)
        {
            Role role = await db.Queryable<Role>().Where(r => r.Eid == eid && r.Id == id).SingleAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = role,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rid"></param>
        /// <param name="pmids"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostAddpermission([FromForm] long eid, [FromForm] long rid, [FromForm] long[] pmids)
        {
            // 先清空该角色所有权限
            await db.Deleteable<RolePermission>().Where(rp => rp.Eid == eid && rp.Rid == rid).ExecuteCommandAsync();

            List<RolePermission> rolePermissions = new();
            foreach (long pmid in pmids)
            {
                rolePermissions.Add(new RolePermission { Eid = eid, Rid = rid, Pmid = pmid });
            }
            int affrows = await db.Insertable<RolePermission>(rolePermissions).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 获取权限
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostGetpermission([FromForm] long eid, [FromForm] long rid)
        {
            JArray data = new();
            List<long> pmids = await db.Queryable<RolePermission>().Where(rp => rp.Eid == eid).Where(rp => rp.Rid == rid).Select(rp => rp.Pmid).ToListAsync();
            data = await GetRolePermissionTreeData(eid, 0, pmids);
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        [NonAction]
        public async Task<JArray> GetRolePermissionTreeData([FromForm] long eid, long bspid, List<long> pmids)
        {
            JArray data = new();
            List<EnterprisePermission> enterprisepermissions = await db.Queryable<EnterprisePermission>().Where(ep => ep.Eid == eid).Where(ep => ep.ParentId == bspid).ToListAsync();
            if (enterprisepermissions?.Count > 0)
            {
                foreach (var enterprisepermission in enterprisepermissions)
                {
                    JObject jo_enterprisepermission = JObject.FromObject(enterprisepermission);
                    if (pmids.Contains(enterprisepermission.Id))
                    {
                        jo_enterprisepermission.Add("checked", true);
                    }
                    else
                    {
                        jo_enterprisepermission.Add("checked", false);
                    }
                    jo_enterprisepermission.Add("children", GetRolePermissionTreeData(eid, enterprisepermission.Bspmid, pmids).Result);
                    data.Add(jo_enterprisepermission);
                }
            }

            return data;
        }

        /// <summary>
        /// 增加员工
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rid"></param>
        /// <param name="epids"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostAddEmployee([FromForm] long eid, [FromForm] long rid, [FromForm] long[] epids)
        {
            // 1.先清空当前角色所有用户
            await db.Deleteable<RoleEmployee>().Where(ru => ru.Rid == rid).ExecuteCommandAsync();
            // 2.再从新增加所有用户
            long affrows = 0;
            if (epids?.Length > 0)
            {
                List<RoleEmployee> roleemployees = new();
                foreach (var uid in epids)
                {
                    roleemployees.Add(new RoleEmployee { Eid = eid, Rid = rid, Epid = uid });
                }
                affrows = await db.Insertable<RoleEmployee>(roleemployees).ExecuteCommandAsync();
            }
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 获取员工
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rid"></param>
        /// <param name="dpid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostGetemployee([FromForm] long eid, [FromForm] long rid, [FromForm] long dpid)
        {
            // 查询出来该企业所有员工
            //List<long> epids = await db.Queryable<EmployeeEnterprise>().Where(ee => ee.Eid == eid).Select(ee => ee.Epid).ToListAsync();

            /*
            List<long> znepids = await db.Queryable<RoleEmployee>().Where(ru => ru.Eid == eid).Where(ru => ru.Rid == rid).Select(ru => ru.Epid).ToListAsync();
            znepids.Add(-1);
            //List<long> zwepids = await db.Queryable<RoleEmployee>().Where(ru => ru.Eid == eid).Where(ru => ru.Rid != rid).Select(ru => ru.Epid).ToListAsync();
            //zwepids.Add(-1);
            epids.RemoveAll(id => znepids.Contains(id));
            epids.Add(-1);
            List<long> zwepids = epids;*/
            List<long> znepids = await db.Queryable<RoleEmployee>().Where(ru => ru.Eid == eid).Where(ru => ru.Rid == rid).Select(ru => ru.Epid).ToListAsync();
            znepids.Add(-1);
            List<Employee> znemployees = await db.Queryable<Employee>().Where(ep => ep.DefaultEid == eid).Where(ep => znepids.Contains(ep.Id)).ToListAsync();
            List<Employee> zwemployees = await db.Queryable<Employee>().Where(ep => ep.DefaultEid == eid).Where(ep => !znepids.Contains(ep.Id)).WhereIF(dpid != 0, u => u.Dpid == dpid).ToListAsync();
            JObject data = new();
            data.Add("znemployees", znemployees == null ? null : JArray.FromObject(znemployees));
            data.Add("zwemployees", zwemployees == null ? null : JArray.FromObject(zwemployees));
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 返回checkedids
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostGetcheckedids([FromForm] long eid, [FromForm] long rid)
        {
            //string checkedids = await db.Queryable<Role>().Where(r => r.Eid == eid && r.Id == rid).Select(r => r.CheckedIds).SingleAsync();
            //return new JsonResult(new RESTfulResult<object>
            //{
            //    StatusCode = 200,
            //    Succeeded = true,
            //    Data = string.IsNullOrEmpty(checkedids) ? null : JArray.Parse(checkedids),
            //    Errors = null,
            //    Extras = UnifyContext.Take(),
            //    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            //});

            List<long> pmids = await db.Queryable<RolePermission>().Where(r => r.Eid == eid && r.Rid == rid).Select(r => r.Pmid).ToListAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = pmids,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
